package com.hyt.it.ogt.kq.main.controller.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hyt.core.abstractclass.AbstractController;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.service.bm.feign.tps.TpsClient;
import com.hyt.it.ogt.kq.service.bm.service.IUserPermissionService;
import com.hyt.loginfo.model.Organization;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.model.UserDetailsEntity;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.model.QuotEditor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuq
 * @date 2021/1/5 09:42
 * @Description
 */
@Slf4j
public abstract class BaseController extends AbstractController {

    @Autowired
    private IBaseLoginService iBaseLoginService;

    @Autowired
    private TpsClient tpsClient;

    @Autowired
    private IUserPermissionService iUserPermissionService;


    /**
     * 获取登录用户信息
     *
     * @return User
     */
    public User getUser() {
        return iBaseLoginService.getSysUser();
    }


    public User getUserByToken(String token) {
        return iBaseLoginService.getSysUser(token);
    }

    /**
     * 获取登录用户ID
     *
     * @return String
     */
    public String getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getName();
    }

    /**
     * 获取机构ID
     *
     * @return String
     */
    public String getOfficeId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object obj = authentication.getPrincipal();
            if (obj instanceof UserDetailsEntity) {
                UserDetailsEntity userDetailsEntity = (UserDetailsEntity) obj;
                log.info("## getOfficeIdL{}", FastJsonUtil.getBeanToJson(userDetailsEntity));
                return userDetailsEntity.getOfficeId();
            }
            return iBaseLoginService.getOfficeId();
        } catch (Exception e) {
            throw new KqException(ResponseCode.ORGANIZATION_GET_ID_EXCEPTION.getCode(),
                    ResponseCode.ORGANIZATION_GET_ID_EXCEPTION.getMsg());
        }
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(String.class, new QuotEditor()); //双引号特殊处理
    }

    @SuppressWarnings("unchecked")
    public String getBmProjectQrCodeUrl(String officeId) {
        Map<String, Object> map = new HashMap<String, Object>();
        String qrCodeUr = null;
        if (StrUtil.isEmpty(officeId)) {
            return qrCodeUr;
        }
        try {
            String scene = "offId=";
            if (officeId.length() > 24) {
                scene = scene + officeId.substring(0, 24);
            } else {
                scene = scene + officeId;
            }
            map = (Map<String, Object>) tpsClient.getBmQRCodeHwCloud(officeId, scene, "pages/home/index", 260);
            log.info("getBmQRCodeHwCloud scene:{},result:{}", scene, JSON.toJSON(map));
        } catch (Exception e) {
            log.error("## getBmQRCodeHwCloud error", e);
        }
        if (null != map) {
            qrCodeUr = String.valueOf(map.get("obj"));
        }
        return qrCodeUr;
    }

    public List<String> getPermissionList(String projectId) {
        List<String> permissionList = new ArrayList<>();
        boolean flag = iUserPermissionService.needCheckOfficePermission(projectId);
        if (flag) {
            permissionList = iUserPermissionService.queryPermissionByUserId(projectId, iBaseLoginService.getUserId());
            if (CollUtil.isEmpty(permissionList)) {
                permissionList = new ArrayList<String>();
                permissionList.add("NoPermission");//如果是无权限，设置一个不存在的权限
            }
        }
        return permissionList;
    }

    public List<String> getPermissionListV2(String projectId) {
        List<String> permissionList = new ArrayList<>();
        boolean flag = iUserPermissionService.needCheckAreaPermission(projectId);
        if (flag) {
            permissionList = iUserPermissionService.queryPermissionByUserId(projectId, iBaseLoginService.getUserId());
            if (CollUtil.isEmpty(permissionList)) {
                permissionList = new ArrayList<String>();
                permissionList.add("NoPermission");//如果是无权限，设置一个不存在的权限
            }
        } else {
            permissionList.add("-1");
        }
        return permissionList;
    }

    public String getClientRequestToken(String authHeader) {
        if (StrUtil.isNotEmpty(authHeader)) {
            authHeader = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, CharSequenceUtil.EMPTY).trim();
            authHeader = authHeader.replace("bearer", CharSequenceUtil.EMPTY).trim();
            return authHeader;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        OAuth2AuthenticationDetails authenticationDetails = null;
        try {
            authenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
        } catch (Exception e) {

        }
        if (null == authenticationDetails) {
            return null;
        }
        String token = authenticationDetails.getTokenValue();
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        return token;
    }


    /**
     * 获取部门ID
     *
     * @return String
     */
    public String getDeptId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object obj = authentication.getPrincipal();
            if (obj instanceof UserDetailsEntity) {
                UserDetailsEntity userDetailsEntity = (UserDetailsEntity) obj;
                String deptId = userDetailsEntity.getDeptId();
                if (StrUtil.isNotEmpty(deptId)) {
                    return deptId;
                }
            }
            return iBaseLoginService.getDeptId();
        } catch (Exception e) {
            throw new KqException(ResponseCode.DEPT_GET_ID_EXCEPTION.getCode(),
                    ResponseCode.DEPT_GET_ID_EXCEPTION.getMsg());
        }
    }

    /**
     * 获取部门详情
     *
     * @return String
     */
    public Organization getDeptInfo() {
        try {
            return iBaseLoginService.getDeptInfo();
        } catch (Exception e) {
            throw new KqException(ResponseCode.DEPT_GET_INFO_EXCEPTION.getCode(),
                    ResponseCode.DEPT_GET_INFO_EXCEPTION.getMsg());
        }
    }


}
